#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OCR服务调用模块
用于Django后端调用Flask OCR服务
"""

import requests
import json
import os
from django.conf import settings
from django.core.files.uploadedfile import UploadedFile
import tempfile

class OCRService:
    """OCR服务调用类"""
    
    def __init__(self, base_url='http://localhost:5000'):
        """
        初始化OCR服务
        
        Args:
            base_url: OCR服务的基础URL
        """
        self.base_url = base_url.rstrip('/')
        self.timeout = 30  # 请求超时时间（秒）
    
    def health_check(self):
        """检查OCR服务是否可用"""
        try:
            response = requests.get(
                f'{self.base_url}/api/health',
                timeout=5
            )
            if response.status_code == 200:
                return True, response.json()
            else:
                return False, f"服务状态异常: {response.status_code}"
        except requests.exceptions.RequestException as e:
            return False, f"无法连接到OCR服务: {str(e)}"
    
    def recognize_single_image(self, image_file, filename=None):
        """
        识别单张图片
        
        Args:
            image_file: 图片文件对象（Django UploadedFile或文件路径）
            filename: 文件名（可选）
            
        Returns:
            dict: 识别结果
        """
        try:
            # 处理不同类型的文件输入
            if isinstance(image_file, UploadedFile):
                # Django UploadedFile对象
                files = {'image': (filename or image_file.name, image_file, image_file.content_type)}
            elif isinstance(image_file, str):
                # 文件路径
                if not os.path.exists(image_file):
                    return {
                        'success': False,
                        'error': f'文件不存在: {image_file}'
                    }
                files = {'image': open(image_file, 'rb')}
            else:
                # 其他文件对象
                files = {'image': image_file}
            
            # 发送请求
            response = requests.post(
                f'{self.base_url}/api/ocr/recognize',
                files=files,
                timeout=self.timeout
            )
            
            # 关闭文件（如果是文件路径）
            if isinstance(image_file, str) and 'files' in locals():
                files['image'].close()
            
            if response.status_code == 200:
                return response.json()
            else:
                return {
                    'success': False,
                    'error': f'OCR服务错误: {response.status_code} - {response.text}'
                }
                
        except requests.exceptions.Timeout:
            return {
                'success': False,
                'error': 'OCR服务请求超时'
            }
        except requests.exceptions.RequestException as e:
            return {
                'success': False,
                'error': f'OCR服务请求失败: {str(e)}'
            }
        except Exception as e:
            return {
                'success': False,
                'error': f'处理失败: {str(e)}'
            }
    
    def recognize_batch_images(self, image_files):
        """
        批量识别图片
        
        Args:
            image_files: 图片文件列表
            
        Returns:
            dict: 批量识别结果
        """
        try:
            files = []
            
            # 处理文件列表
            for i, image_file in enumerate(image_files):
                if isinstance(image_file, UploadedFile):
                    files.append(('images', (image_file.name, image_file, image_file.content_type)))
                elif isinstance(image_file, str):
                    if os.path.exists(image_file):
                        files.append(('images', open(image_file, 'rb')))
                else:
                    files.append(('images', image_file))
            
            # 发送请求
            response = requests.post(
                f'{self.base_url}/api/ocr/batch',
                files=files,
                timeout=self.timeout * len(image_files)  # 批量处理增加超时时间
            )
            
            # 关闭文件
            for _, file_obj in files:
                if hasattr(file_obj, 'close'):
                    file_obj.close()
            
            if response.status_code == 200:
                return response.json()
            else:
                return {
                    'success': False,
                    'error': f'OCR服务错误: {response.status_code} - {response.text}'
                }
                
        except requests.exceptions.Timeout:
            return {
                'success': False,
                'error': 'OCR服务请求超时'
            }
        except requests.exceptions.RequestException as e:
            return {
                'success': False,
                'error': f'OCR服务请求失败: {str(e)}'
            }
        except Exception as e:
            return {
                'success': False,
                'error': f'处理失败: {str(e)}'
            }

# 全局OCR服务实例 - 指向远程服务器
ocr_service = OCRService(base_url='http://192.168.0.169:5000')

def get_ocr_service():
    """获取OCR服务实例"""
    return ocr_service

def recognize_image(image_file, filename=None):
    """
    便捷函数：识别单张图片
    
    Args:
        image_file: 图片文件
        filename: 文件名
        
    Returns:
        dict: 识别结果
    """
    return ocr_service.recognize_single_image(image_file, filename)

def recognize_images_batch(image_files):
    """
    便捷函数：批量识别图片
    
    Args:
        image_files: 图片文件列表
        
    Returns:
        dict: 批量识别结果
    """
    return ocr_service.recognize_batch_images(image_files)

def check_ocr_service():
    """
    便捷函数：检查OCR服务状态
    
    Returns:
        tuple: (是否可用, 状态信息)
    """
    return ocr_service.health_check()
